#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Go Network Monitoring 服务安装脚本
用于下载并安装 go-network-monitoring 服务到 Linux 系统
支持自定义程序链接、服务名称等参数
"""

import os
import sys
import subprocess
import urllib.request
import shutil
import argparse
from pathlib import Path

# 默认配置值
DEFAULT_DOWNLOAD_URL = "https://gitee.com/liumou_site/go-network-monitoring/releases/download/v1.2.2/com.liumou.go-network-monitoring_v1.2.2_linux-X86_64"
DEFAULT_SERVICE_NAME = "go-network-monitoring"
DEFAULT_DESCRIPTION = "Go Network Monitoring Service"


class ServiceInstaller:
    def __init__(self, download_url, service_name, target_path, description):
        self.download_url = download_url
        self.service_name = service_name
        self.target_path = target_path or f"/usr/bin/{service_name}"
        self.description = description
        
        # 生成相关路径
        self.service_file_path = f"/etc/systemd/system/{service_name}.service"
        
    def check_root(self):
        """检查是否具有 root 权限"""
        if os.geteuid() != 0:
            print("错误：需要 root 权限运行此脚本")
            print("请使用 sudo 运行：sudo python3 install_service.py")
            sys.exit(1)
            
    def download_binary(self):
        """下载二进制文件"""
        print("正在下载 go-network-monitoring 二进制文件...")
        try:
            urllib.request.urlretrieve(self.download_url, self.target_path)
            os.chmod(self.target_path, 0o755)
            print(f"✓ 成功下载到 {self.target_path}")
        except Exception as e:
            print(f"错误：下载失败 - {e}")
            sys.exit(1)
            
    def create_service_file(self):
        """创建 systemd 服务文件"""
        service_content = f"""[Unit]
Description=Go Network Monitoring Service
After=network.target

[Service]
Type=simple
User=root
ExecStart={self.target_path}
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
"""
        
        try:
            with open(self.service_file_path, 'w') as f:
                f.write(service_content)
            print(f"✓ 成功创建服务文件 {self.service_file_path}")
        except Exception as e:
            print(f"错误：创建服务文件失败 - {e}")
            sys.exit(1)
            
    def enable_and_start_service(self):
        """启用并启动服务"""
        commands = [
            ["systemctl", "daemon-reload"],
            ["systemctl", "enable", self.service_name],
            ["systemctl", "start", self.service_name]
        ]
        
        for cmd in commands:
            try:
                subprocess.run(cmd, check=True, capture_output=True, text=True)
            except subprocess.CalledProcessError as e:
                print(f"错误：执行 {' '.join(cmd)} 失败 - {e}")
                sys.exit(1)
                
        print("✓ 服务已启用并启动")
        
    def check_service_status(self):
        """检查服务状态"""
        try:
            result = subprocess.run(["systemctl", "status", self.service_name], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print("\n服务状态：")
                print(result.stdout)
            else:
                print("警告：无法获取服务状态")
        except Exception as e:
            print(f"警告：检查服务状态失败 - {e}")
            
    def uninstall_service(self):
        """卸载服务"""
        print("正在卸载服务...")
        commands = [
            ["systemctl", "stop", self.service_name],
            ["systemctl", "disable", self.service_name]
        ]
        
        for cmd in commands:
            try:
                subprocess.run(cmd, capture_output=True)
            except:
                pass  # 忽略停止/禁用时的错误
                
        # 删除文件
        try:
            if os.path.exists(self.service_file_path):
                os.remove(self.service_file_path)
            if os.path.exists(self.target_path):
                os.remove(self.target_path)
            subprocess.run(["systemctl", "daemon-reload"], capture_output=True)
            print("✓ 服务已成功卸载")
        except Exception as e:
            print(f"错误：卸载失败 - {e}")
            
    def install(self):
        """执行完整安装流程"""
        print("开始安装 Go Network Monitoring 服务...")
        self.check_root()
        self.download_binary()
        self.create_service_file()
        self.enable_and_start_service()
        self.check_service_status()
        print("\n🎉 安装完成！")
        print(f"服务名称: {self.service_name}")
        print("管理命令:")
        print(f"  启动: sudo systemctl start {self.service_name}")
        print(f"  停止: sudo systemctl stop {self.service_name}")
        print(f"  重启: sudo systemctl restart {self.service_name}")
        print(f"  状态: sudo systemctl status {self.service_name}")


def create_parser():
    """创建命令行参数解析器"""
    parser = argparse.ArgumentParser(
        description="Go Network Monitoring 服务安装脚本",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例用法:
  %(prog)s                                    # 使用默认配置安装
  %(prog)s --url http://example.com/app       # 自定义下载链接
  %(prog)s --name my-monitor --desc "自定义描述"  # 自定义服务名称和描述
  %(prog)s --path /opt/monitor                # 自定义安装路径
  %(prog)s uninstall                          # 卸载服务
        """
    )
    
    parser.add_argument('--url', '--download-url',
                        dest='download_url',
                        default=DEFAULT_DOWNLOAD_URL,
                        help=f'程序下载链接 (默认: {DEFAULT_DOWNLOAD_URL})')
    
    parser.add_argument('--name', '--service-name',
                        dest='service_name',
                        default=DEFAULT_SERVICE_NAME,
                        help=f'服务名称 (默认: {DEFAULT_SERVICE_NAME})')
    
    parser.add_argument('--path', '--target-path',
                        dest='target_path',
                        default=None,
                        help='安装目标路径 (默认: /usr/bin/[服务名称])')
    
    parser.add_argument('--desc', '--description',
                        dest='description',
                        default=DEFAULT_DESCRIPTION,
                        help=f'服务描述 (默认: {DEFAULT_DESCRIPTION})')
    
    parser.add_argument('action',
                        nargs='?',
                        choices=['install', 'uninstall'],
                        default='install',
                        help='操作: install 或 uninstall (默认为: install)')
    
    parser.add_argument('--version', '-v',
                        action='version',
                        version='%(prog)s 2.0.0')
    
    return parser


def main():
    parser = create_parser()
    args = parser.parse_args()
    
    # 创建安装器实例，使用命令行参数
    installer = ServiceInstaller(
        download_url=args.download_url,
        service_name=args.service_name,
        target_path=args.target_path,
        description=args.description
    )
    
    # 执行操作
    if args.action == 'uninstall':
        installer.check_root()
        installer.uninstall_service()
    else:
        installer.install()


if __name__ == "__main__":
    main()